//
//  SingleImageView.swift
//  YoruNeko
//
//  Created by Kotori on 2021/6/30.
//

import SwiftUI

struct SingleImageView: View {
    var image: UIImage = UIImage(imageLiteralResourceName: "bg")
    
    /* 放缩手势 */
    @Binding var currScale: CGFloat// = CGFloat(1.0)
    @Binding var lastScale: CGFloat// = CGFloat(1.0)
    @Binding var currAngle: Angle// = .zero
    @Binding var lastAngle: Angle// = .zero
    
    func scaleChange(isUp: Bool) {
        if isUp {
            if currScale + CGFloat(0.5) <= CGFloat(5.0) {
                currScale += CGFloat(0.5)
            }
        } else {
            if currScale - CGFloat(0.5) >= CGFloat(0.5) {
                currScale -= CGFloat(0.5)
            }
        }
        lastScale = currScale
    }
    
    //CW ClockWise 顺时针
    func rotate(isCW: Bool) {
        if isCW {
            currAngle += .init(degrees: 90.0)
            
        } else {
            currAngle -= .init(degrees: 90.0)
        }
        lastAngle = currAngle
    }
    
    var magnification: some Gesture {
        MagnificationGesture()
            .onChanged() { scale in
                if currScale + (scale-CGFloat(1.0))/2 <= CGFloat(5.0) && currScale + (scale-CGFloat(1.0))/2 >= CGFloat(0.5) {
                    self.currScale = self.lastScale + (scale-CGFloat(1.0))/2
                }
            }
            .onEnded() { scale in
                self.lastScale = self.currScale
            }
            .simultaneously(with: RotationGesture()
                                .onChanged({ angle in
                                    currAngle = lastAngle + angle
                                })
                                .onEnded({ angle in
                                    lastAngle = currAngle
                                })
            )
    }
    
    
    
    var body: some View {
        Image(uiImage: image)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .background(Color.white.opacity(0.9))
            .scaleEffect(currScale)
            .rotationEffect(currAngle)
            .gesture(magnification)
            .animation(.default)
            .onLongPressGesture {
                //长按图片弹出菜单，可选保存
            }
    }
}

